Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Operators

Comparison operators

Comparison operators are fundamental tools in Python for evaluating relationships between values. They compare two operands and return a Boolean result (True or False) based on the specified condition. These operators are essential for making decisions and controlling the flow of your program through conditional statements like if, elif, and else. List of Comparison Operators: Equal to (==) Checks if two values are identical in value and data type. Example: x = 10; y = 10; x == y evaluates to True. Not Equal to (!=) Determines if two values are not the same. Example: a = "apple"; b = "banana"; a != b evaluates to True. Less Than (<) Compares if the value on the left is strictly less than the value on the right. Example: c = 5; d = 8; c < d evaluates to True. Greater Than (>) Checks if the value on the left is strictly greater than the value on the right. Example: e = 12; f = 7; e > f evaluates to True. Less Than or Equal To (<=) Evaluates if the value on the left is either less than or equal to the value on the right. Example: g = 3; h = 3; g <= h evaluates to True (since 3 is equal to 3). Greater Than or Equal To (>=) Determines if the value on the left is either greater than or equal to the value on the right. Example: i = 15; j = 10; i >= j evaluates to True (since 15 is greater than 10).
Example of comparison operator in python x=10 y=20 print(x == y) print(x != y) print(x > y) print(x < y) print(x >= y) print(x <= y)

Output

False True False True False True
Important Notes ⮞ Comparison operators work with various data types in Python, including numbers, strings, booleans, and some sequences (like lists and tuples) for basic ordering comparisons. However, the order might differ for custom data types you define. ⮞ When comparing sequences, the comparison is based on the elements at corresponding positions, stopping at the first mismatch. For example, [1, 2, 3] < [1, 2, 4] is True because 3 is less than 4. ⮞ Be cautious when comparing floating-point numbers due to potential precision issues. It's generally recommended to use a small tolerance value with abs(x - y) < tolerance for floating-point comparisons instead of strict equality (==).

  📌TAGS

★python ★ operators ★ comparison

Tutorials